package com.seecen.controller;

import com.seecen.pojo.dto.TallyDto;
import com.seecen.pojo.vo.BillDetailVO;
import com.seecen.pojo.vo.ChartDataVO;
import com.seecen.pojo.vo.RankingItemVO;
import com.seecen.service.TallyService;
import com.seecen.utils.JwtHelper;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @program: SharkBookkeeping-end
 * @description: 记账统计控制器
 * @author: XXW
 * @create: 2025-10-16 19:39
 * @version: 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/tally")
@CrossOrigin
public class TallyController {

    @Autowired
    private TallyService tallyService;

    @Autowired
    private JwtHelper jwtHelper;

    /**
     * 获取图表数据
     * @param type 类型：expense-支出，income-收入
     * @param period 周期：week-周，month-月，year-年
     * @param token 用户token
     * @return 图表数据
     */
    @GetMapping("/data")
    public Result<ChartDataVO> getChartData(
            @RequestParam String type,
            @RequestParam String period,
            @RequestHeader String token) {
        
        log.info("获取图表数据 - type: {}, period: {}", type, period);
        
        // 从token获取用户ID
        Long userId = jwtHelper.getUserId(token);
        
        // 调用服务获取数据
        ChartDataVO chartData = tallyService.getChartData(type, period, userId);
        
        return Result.ok(chartData);
    }

    /**
     * 获取排行榜数据
     * @param type 类型：expense-支出，income-收入
     * @param period 周期：week-周，month-月，year-年
     * @param token 用户token
     * @return 排行榜数据列表
     */
    @GetMapping("/ranking")
    public Result<List<RankingItemVO>> getRankingData(
            @RequestParam String type,
            @RequestParam String period,
            @RequestHeader String token) {
        
        log.info("获取排行榜数据 - type: {}, period: {}", type, period);
        
        // 从token获取用户ID
        Long userId = jwtHelper.getUserId(token);
        
        // 调用服务获取数据
        List<RankingItemVO> rankingData = tallyService.getRankingData(type, period, userId);
        
        return Result.ok(rankingData);
    }

    /**
     * 获取账单明细
     * @param year 年份
     * @param month 月份
     * @param accountId 账本ID（可选，不传则查询所有账本）
     * @param token 用户token
     * @return 账单明细数据
     */
    @GetMapping("/detail")
    public Result<BillDetailVO> getBillDetail(
            @RequestParam Integer year,
            @RequestParam Integer month,
            @RequestParam(required = false) Long accountId,
            @RequestHeader String token) {
        
        log.info("获取账单明细 - year: {}, month: {}, accountId: {}", year, month, accountId);
        
        // 从token获取用户ID
        Long userId = jwtHelper.getUserId(token);
        
        // 调用服务获取数据
        BillDetailVO billDetail = tallyService.getBillDetail(year, month, accountId, userId);
        
        return Result.ok(billDetail);
    }

    @PostMapping("/save")
    public Result<String> saveTally(@RequestBody TallyDto tallyDto, @RequestHeader String token) {
        try {
            // 从Token获取用户ID
            Long userId = jwtHelper.getUserId(token);
            if (userId == null) {
                return Result.build(null, ResultCode.NOTLOGIN);
            }

            // 调用Service处理业务逻辑
            boolean success = tallyService.saveTallyByDto(tallyDto, userId);
            if (success) {
                return Result.ok("记账成功");
            } else {
                return Result.build("记账失败", 500, "保存失败");
            }
        } catch (Exception e) {
            log.error("记账异常", e);
            return Result.build("服务器错误：" + e.getMessage(), 500, "服务器内部错误");
        }
    }

    /**
     * 获取账户概览数据
     * @param token 用户token
     * @return 账户概览数据
     */
    @GetMapping("/overview")
    public Result<Object> getAccountOverview(@RequestHeader String token) {
        try {
            log.info("获取账户概览数据");
            
            // 从token获取用户ID
            Long userId = jwtHelper.getUserId(token);
            if (userId == null) {
                return Result.build(null, ResultCode.NOTLOGIN);
            }
            
            // 调用服务获取数据
            Object overviewData = tallyService.getAccountOverview(userId);
            
            return Result.ok(overviewData);
        } catch (Exception e) {
            log.error("获取账户概览数据失败", e);
            return Result.build(null, 500, "获取账户概览数据失败：" + e.getMessage());
        }
    }
}